package com.dingding.aop;

import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * TODO
 *
 * @author Dingxintao
 * @date 2023/9/20 11:29
 */
@Component
public class AddResponseHeaderFilter extends OncePerRequestFilter {

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
                                    FilterChain chain) throws ServletException, IOException {
        HttpServletRequest requestWrapper = null;

        String header = response.getHeader("Set-Cookie");
        header = header == null ? "HttpOnly;" : (header + "HttpOnly;");
        response.setHeader("Set-Cookie", header);

        if (request instanceof HttpServletRequest) {
            String method = request.getMethod();
            String contentType = request.getContentType() == null ? "" : request.getContentType();
            // 如果是POST请求并且不是文件上传
            if (HttpMethod.POST.name().equals(method) && contentType.indexOf(MediaType.MULTIPART_FORM_DATA_VALUE) < 0) {
                // 重新生成ServletRequest  这个新的 ServletRequest 获取流时会将流的数据重写进流里面
                requestWrapper = new XssHttpServletRequestWrapper(request);
            }
        }
        if (requestWrapper == null) {
            chain.doFilter(request, response);
        } else {
            chain.doFilter(requestWrapper, response);
        }

    }
}
